<?php

// 充值  升级会员
class UpgradeAction extends UserAction
{
    //魔术方法
    public function __construct()
    {
        parent::__construct();
    }

    //订单列表
    public function index()
    {

        $this->webtitle = "wqp米有项目框架";
        $this->display();
    }

    //vip 特权
    public function vip_tq()
    {
        $this->display();
    }

    //订单信息
    public function upgrade_detail()
    {
        $memberinfo_de = $this->getMemberDetail();
        $this->assign("data", $data);
        $this->display();
    }

    //直接下单买
    public function set_order()
    {
        $return_data['status'] = 0;
        $address_id = $_REQUEST['address_id'];
        $uid = $_SESSION['member']['uid'];
        if (empty($_SESSION['member']['mobile'])) {
            //未绑定  手机
            $return_data['status'] = 2;
            $return_data['error'] = '请完善资料';
            echo json_encode($return_data);
            die;
        }
        if (empty($address_id)) {
            $return_data['error'] = '请选择收货地址';
            echo json_encode($return_data);
            die;
        }
        $address = M('g_user_address')->where(array('address_id' => $address_id, 'user_id' => $uid))->find();
        if (empty($address)) {
            $return_data['error'] = '收货地址不存在';
            echo json_encode($return_data);
            die;
        }
        //购买开关
        $buy_switch = M('sys_param')->where(array('param_code' => 'buy_switch'))->getField('param_value');
        if (empty($buy_switch)) {
            $return_data['error'] = '管理员已关闭交易';
            echo json_encode($return_data);
            die;
        }
        //pay_name  //wxpay
        $cart_model = D('Cart');
        $list = $this->cheak_goods();
        //计算价格
        $list = $cart_model->getCartSettlement($list);
        if (empty($list['status'])) {
            $return_data['error'] = $list['error'];
            echo json_encode($return_data);
            die;
        }
        if($list['need_pay']<68){
            $order_data['shipping_fee']=10;//订单金额小于 68 须支付运费10元
        }
        $goods = $list['goods_list'];
        $time = time();
        $pay_sn = makePaySn($uid);
        $order_data['order_sn'] = $pay_sn;
        $order_data['user_id'] = $uid;
        $order_data['consignee'] = $address['consignee'];
        $order_data['province'] = $address['province'];
        $order_data['city'] = $address['city'];//
        $order_data['district'] = $address['area'];//
        $order_data['address'] = $address['address_name'] . $address['address'];//用户消费时的折扣
        $order_data['zipcode'] = $address['zipcode'];//用
        $order_data['tel'] = $address['tel'];//
        $order_data['mobile'] = $address['mobile'];//
        $order_data['email'] = $address['email'];//
        $order_data['best_time'] = $address['best_time'];//收货人的最佳送货时间
        $order_data['sign_building'] = $address['sign_building'];//收货人的地址的标志性建筑

        $order_data['is_gift'] = $list['is_gift'];//活动类型0 无 1 限时抢购

        $order_data['is_upgrade'] = $list['is_upgrade'];////升级产品

        $order_data['goods_amount'] = $list['tolal'];//商品总金额
        $order_data['order_amount'] = $list['need_pay'];//应付款金额
        $order_data['order_cost'] = $list['order_cost'];//成本

        $order_data['pay_note'] = I('pay_note');//备注
        $order_data['add_time'] = $time;
        //$should_pay = $list['need_pay'];  //应付款金额

        $order_pay_data['buyer_id'] = $uid;
        $order_pay_data['pay_sn'] = $pay_sn;

        $order_model = M('g_order_info');
        $order_goods_model = M('g_order_goods');
        $order_pay_model = M('g_order_pay');


        $order_model->startTrans();//开起事务
        $order_goods_model->startTrans();//开起事务
        $order_pay_model->startTrans();//开起事务

        $add_order = $order_model->add($order_data);

        if ($add_order === false) {
            $return_data['error'] = "订单生成失败，请稍后再试.";
            $order_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            echo json_encode($return_data);
            die;
        }

        $add_order_pay = $order_pay_model->add($order_pay_data);
        $good_list = $goods;
        foreach ($good_list as $key => $value) {
            $order_good_data['order_id'] = $add_order;
            $order_good_data['goods_id'] = $value['goods_id'];
            $order_good_data['goods_name'] = $value['goods_name'];//商品名
            $order_good_data['goods_sn'] = $value['goods_sn'];//商品的唯一货号
            $order_good_data['goods_price'] = $value['goods_price'];//商品价格
            $order_good_data['market_price'] = $value['market_price'];//商品价格
            $order_good_data['purchase_price'] = $value['purchase_price'];//进价
            $order_good_data['goods_number'] = $value['goods_number'];//商品数量
            $order_good_data['goods_image'] = $value['goods_img'];//
            $order_good_data['goods_attr_id'] = $value['goods_attr_id'];//商品实际成交价
            $order_good_data['goods_attr'] = $value['goods_attr'];//商家id
            $order_good_data['share_card'] = $value['share_card'];//分享者 card
            $order_good_data['share_id'] = $value['share_card'];//分享者 id

            $order_good_data['share_money'] = $value['share_money'];//分享返利金额
            $order_good_data['is_refund'] = $value['is_refund'];//是否可退货 1是 0否
            $order_good_data['goods_shipping'] = $value['goods_shipping'];//包邮方式 默认SF顺风包邮
            $order_good_data['shipping_code'] = $value['shipping_code'];//包邮方式code
            $order_good_data['offline'] = $value['offline'];//货到付款
            $order_good_data['is_exchange'] = $value['is_exchange'];////是否可退货 1是 0否
            $order_good_data['is_gift'] = $value['rec_type'];//活动类型0 无 1 限时抢购
            $order_good_data['promote_start_date'] = $value['promote_start_date'];
            $order_good_data['promote_end_date'] = $value['promote_end_date'];
            $order_good_data['is_upgrade'] = $value['is_upgrade'];//升级产品
            $add_order_goods[] = $order_goods_model->add($order_good_data);

        }

        $add_order_goods = array_unique($add_order_goods);//去重
        //in_array如果设置该参数为 true，则检查搜索的数据与数组的值的类型是否相同。
        if ($add_order !== false && $add_order_pay !== false && in_array(false, $add_order_goods, true) === false) {
            $return_data['status'] = 1;
            $order_model->commit();//提交事务
            $order_goods_model->commit();//提交事务
            $order_pay_model->commit();//提交事务
            //记录订单日志
            $data = array();
            $data['order_id'] = $add_order;
            $data['order_amount'] = $list['need_pay'];
            M('g_pay_log')->add($data);
            //记录订单日志
            $data = array();
            $data['order_id'] = $add_order;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '用户下单成功';
            $data['log_orderstate'] = '10';
            D('Mallorder')->addOrderLog($data);

            $return_data['need_pay'] = 1;///需要支付 1  不需要支付0


            $return_data['pay_sn'] = $pay_sn;
        } else {
            $order_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            $return_data['error'] = "订单生成失败，请稍后再试.";
        }
        echo json_encode($return_data);
        die;
    }
    //订单详情页

    ///计算 产品价格
    public function cheak_goods()
    {
        $return_data['status'] = 0;
        $goods_attr_id = I('goods_attr_id');
        $goods_number = I('goods_num');
        $goods_id = I('goods_id');
        $share = I('share');
        $data = M('g_goods')->where(array('goods_id' => $goods_id))->find();
        $data = D('Goods')->getGoodsPrice($data);//计算商品价格 限时抢购等
        if (empty($data)) {
            $return_data['error'] = "商品不存在";
            echo json_encode($return_data);
            die;
        }
        if (empty($data['is_on_sale']) || empty($data['is_auditing']) ) {
            $return_data['error'] = "商品已下架";
            echo json_encode($return_data);
            die;
        }
        if ($data['is_buy'] == '-1') {///活动禁止购买
            $return_data['error'] = $data['is_buy_msg'];
            echo json_encode($return_data);
            die;
        }
        $add_data['goods_id'] = $data['goods_id'];
        $add_data['goods_sn'] = $data['goods_sn'];
        $add_data['goods_name'] = $data['goods_name'];
        $add_data['goods_img'] = $data['goods_img'];
        $add_data['rec_type'] = $data['hot_type'];//活动类型0 无 1 限时抢购
        $add_data['share_card'] = $share;

        $add_data['goods_number'] = $goods_number;
        $add_data['goods_attr_id'] = $goods_attr_id;
        $goods_price = $data['shop_price'];
        $market_price = $data['market_price'];
        $attr_str = '';
        $share_money = array();///属性佣金
        if ($goods_attr_id) {
            $goods_attr_model = M('g_goods_attr');

            $goods_price_arr = array();
            $goods_attr = $goods_attr_model->where(array('goods_attr_id' => array('in', $goods_attr_id)))->select();
            foreach ($goods_attr as $keys => $attr_value) {
                if ($attr_value) {
                    if ($attr_value['attr_price']) {
                        $goods_price_arr[] = $attr_value['attr_price'];
                    }
                    if ($attr_value['attr_share_money']) {
                        $share_money[] = $attr_value['attr_share_money'];///属性佣金
                    }
                    $attr_str .= ',' . $attr_value['attr_value'];
                }
            }
        }
        if ($attr_str) {
            $attr_str = substr($attr_str, 1);
        }
        if (!empty($goods_price_arr)) {
            $goods_price_arr = max($goods_price_arr);///属性价格取属性的最大值
        }
        if (empty($goods_price_arr)) {
            $goods_price_arr = 0;
        }
        if (!empty($share_money)) {
            $share_money = max($share_money);///属性佣金属性佣金的最大值
        }
        if (empty($share_money)) {
            $share_money = 0;
        }
        if ($goods_price_arr > 0) {///如果属性价格大于0 取属性价格
            if ($goods_price < $goods_price_arr) {/////计算显示的原价价格
                $market_price = $market_price + ($goods_price_arr - $goods_price);
            }
            //如果属性价格小于商品价格 亦取属性价格
            $goods_price = $goods_price_arr;
        }
        ///商品佣金 =属性佣金属性、商品佣金的最大值

        //$data['share_money']=($share_money>$data['share_money'])?$share_money:$data['share_money'];
        //如果属性佣金属性小于商品属性 亦取属性佣金
        $data['share_money'] = ($share_money > 0) ? $share_money : $data['share_money'];
        $add_data['share_money'] = $data['share_money'];
        $add_data['goods_attr'] = $attr_str;
        $add_data['market_price'] = $market_price;
        $add_data['goods_price'] = $goods_price;
        $add_data['purchase_price'] = $data['purchase_price'];//进价
        $res_data[] = $add_data;
        return $res_data;
    }

    //会员升级商品列表页面
    public function upgrade_goods()
    {
        $p = $_REQUEST['p'];
        $pagesize = 6;
        $p = !empty($p) ? $p : 1;
        $start = ($p - 1) * $pagesize;
        $where['is_delete'] = 0;//商品是否已经删除，0，否；1，已 删除
        $where['is_auditing'] = 1;//是否通过审核 1是0 否
        $where['is_upgrade']=1;//剔除非升级产品
        $field = 'goods_id,goods_name,shop_price,goods_img';
        $count=M('g_goods')->where($where)->count();
        $list = M('g_goods')->field($field)->where($where)->limit($start, $pagesize)->select();

//        var_dump($list);die;
        if (IS_AJAX) {
            echo json_encode($list);
            die;
        }
//        var_dump($list);die;
        $this->count=$count;
        $this->list = $list;
        $this->display();
    }

    //会员商品详细页
    public function goods_detail()
    {
        //微信分享后得回调  zm
        if ($_POST["goods_id"]) {
            $goods = M("upgrade_goods")->where(array("goods_id" => $_POST["goods_id"]))->setInc("goods_share");
            // echo M()->getLastSql();
            if ($goods == true) {
                $re["status"] = 1;
                echo json_encode($re);
                die;
            }
            $re["status"] = 0;
            echo json_encode($re);
            die;
        }
        //浏览量 zm
        $browse = M("upgrade_goods")->where(array("goods_id" => $_GET['id']))->setInc("goods_browse");
        //
        $g_where["goods_id"] = array("eq", $_GET["id"]);
        $g_where['is_delete'] = 0;
        //$g_where['is_show']=1;//上架
        $data = D("Upgrade_goods")->getGoodsInfo($g_where);
        //图片
        if ($data) {
            $data = D('Upgrade_goods')->getGoodsPrice($data);//计算商品价格 限时抢购等
            // var_dump($data);die;
            $this->good_image_url = M('g_goods_gallery')->where(array('goods_id' => $data['goods_id']))->select();
            //商品属性
            $goods_type = $data['goods_type'];
            if (!empty($goods_type)) {
                $goods_id = $data['goods_id'];
                $pre = C('DB_PREFIX');//表前缀
                $goods_attr = M()->table($pre . 'upgrade_goods_attr goods_attr')//
                ->join($pre . 'g_attribute attr on attr.attr_id=goods_attr.attr_id')//
                ->where(array('goods_attr.goods_id' => $goods_id))//
                ->field('goods_attr.*,attr.attr_name,attr.attr_input_type,attr.attr_type')
                    ->order('attr.sort_order desc')->select();
                //attr_type 属性是否多选；0，否；1，是；如 果可以多选，则可以自定义属性，并且可以根据值的不同定不同的价
                //attr_input_type当添加商品时，该属性的添 加类别；0，为手工输入；1，为选择输入；2，为多行文本输入
                if ($goods_attr) {
                    $goods_attr1 = array();
                    foreach ($goods_attr as $key => $value) {
                        if ($value['attr_type']) {
                            $goods_attr1[] = $value;
                            unset($goods_attr[$key]);
                        }
                    }
                    if ($goods_attr1) {
                        $arr = array();
                        foreach ($goods_attr1 as $key => $value) {
                            $arr[$value['attr_id']][] = $value;
                        }
                        if ($arr) {
                            $goods_attr1 = array();
                            foreach ($arr as $key => $value) {
                                $tree = array();
                                foreach ($value as $keys => $val) {
                                    if ($val['attr_value']) {
                                        $tree[] = $val;
                                    }
                                }
                                if ($tree) {
                                    $data_arr = array();
                                    $data_arr['attr_name'] = $value[0]['attr_name'];
                                    $data_arr['tree'] = $tree;
                                    $goods_attr1[] = $data_arr;
                                }
                            }
                        }
                    }
                }
                $this->goods_attr = $goods_attr;
                $this->goods_attr1 = $goods_attr1;
            }
        }
        if ($data['shipping_id'] == 0) {   //判断包邮快递
            $data['shipping_name'] = 'SF顺丰快递';
        } else {
            $shipping_name = M('g_shipping')->field('shipping_name')->where(array('shipping_id' => $data['shipping_id']))->find();
            $data['shipping_name'] = $shipping_name['shipping_name'];
            if (empty($data['shipping_name'])) {
                $data['shipping_name'] = 'SF顺丰快递';
            } elseif ($data['shipping_name'] == '包邮') {
                $data['shipping_name'] = '';
            }
        }
        $this->data = $data;
//       var_dump($data);die;
        //收藏信息
        if ($this->uid) {
            $c_where['goods_id'] = $data['goods_id'];
            $c_where['user_id'] = $this->uid;
            $c_where['is_attention'] = 1;
            $c_count = M('g_collect_goods')->where($c_where)->count();
            $this->collect = $c_count;
        }
        $shar_title = $this->webseting['web_title'] . '-' . $data['goods_name'];
        $shar_len = mb_strlen($shar_title, 'utf-8');
        $rep = ceil($shar_len / 13);
        $replen = $rep * 13 - $shar_len;
        $shar_title_desc = $shar_title;
        if ($replen > 0) {
            $shar_title_desc .= str_repeat('    ', $replen);
        }
        //str_repeat
        $this->shar_url = $url = "http://" . $_SERVER['HTTP_HOST'] . U('wap/upgrade/goods_detail', array('id' => $_GET["id"], 'share' => $this->member_card));
        $this->shar_title = $shar_title;
        $this->shar_desc = $shar_title_desc . "￥" . $data['shop_price'];
        $this->shar_imgurl = "http://" . $_SERVER['HTTP_HOST'] . $data['goods_img'];
        $this->get_weixin();///获取微信 信息
        $this->webtitle = "wqp米有项目框架";
        $this->display();

    }

    //订单显示信息
    public function get_order_msg_data($data = array())
    {
        if (empty($data)) {
            return $data;
        }
        switch ($data['discount_type']) {
            case '1':
                $data['discount_name'] = '抽奖';
                break;

            default:
                # code...
                break;
        }
        $time = time();
        $data['order_amount_all'] = $data['order_amount'];
        $data['discount_price'] = $data['discount'];
        if ($data['pay_status'] == 2) {
            $data['order_amount'] = PriceFormat(floatval($data['order_amount']) - floatval($data['discount']));
        } else {
            if ($data['discount_start_time'] <= $time && $data['discount_end_time'] >= $time) {
                $data['order_amount'] = PriceFormat(floatval($data['order_amount']) - floatval($data['discount']));
            } else {
                $data['discount_price'] = 0;
            }
        }
        return $data;
    }
}